package cn.iocoder.yudao.module.mqtt.framework.mqtt;

import cn.iocoder.yudao.module.mqtt.service.mqtt.MqttConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

/**
 * 条件MQTT配置类
 * 只在数据库可用时才初始化MQTT实例
 *
 * @author 芋道源码
 */
@Slf4j
@Configuration
@ConditionalOnProperty(name = "spring.datasource.dynamic.primary", havingValue = "master")
@Order(1)
public class ConditionalMqttConfiguration implements ApplicationRunner {

    @Autowired(required = false)
    private MqttConfigService mqttConfigService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        if (mqttConfigService == null) {
            log.warn("MqttConfigService不可用，跳过MQTT实例初始化");
            return;
        }
        log.info("开始初始化多MQTT实例...");
        try {
            // 延迟初始化，确保Spring容器完全启动
            Thread.sleep(5000);
            // 初始化所有启用的MQTT实例
            mqttConfigService.initAllEnabledInstances();
            log.info("多MQTT实例初始化完成");
        } catch (Exception e) {
            log.error("多MQTT实例初始化失败，但不会影响应用启动", e);
        }
    }
} 